import axios, { type AxiosInstance, type AxiosResponse } from 'axios'

// 创建 axios 对象
const instance = axios.create({
  baseURL: '/api'
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 获取 token
    const token = localStorage.getItem('TOKEN')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    return Promise.reject(error)
  }
)

const http = {
  get<T>(url: string, params?: any, config?: {}): Promise<T> {
    return new Promise((resolve, reject) => {
      instance
        .get<T>(url, { params, ...config })
        .then((res: AxiosResponse<T>) => {
          resolve(res.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  post<T>(url: string, data?: any, config?: {}): Promise<T> {
    return new Promise((resolve, reject) => {
      instance
        .post<T>(url, data, config)
        .then((res: AxiosResponse<T>) => {
          resolve(res.data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}

export default http
